<template>
    <div class="container">
        <Breadcrumb :items="['menu.member', 'menu.member.index']" />
        <a-card :title="$t('menu.member.index')">
            <a-space fill direction="vertical">
                <a-form layout="inline" :model="searchForm" @submit="handleSearch">
                    <a-form-item field="phone" label="手机号" :hide-label="true">
                        <a-input v-model="searchForm.phone" placeholder="手机号码" allow-clear />
                    </a-form-item>
                    <a-form-item>
                        <a-space>
                            <a-button type="primary" html-type="submit" shape="round">
                                <template #icon><icon-search /></template>
                                搜索
                            </a-button>
                            <a-button shape="round" @click="resetSearch">
                                <template #icon><icon-refresh /></template>
                                重置
                            </a-button>
                        </a-space>
                    </a-form-item>
                </a-form>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }"
                         :pagination="pagination"
                         :scroll="{ x: 2030 }"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="昵称" data-index="nickname" :width="150"/>
                        <a-table-column title="手机号" data-index="phone" :width="150" />
                        <a-table-column title="云豆余额" data-index="score" :width="120">
                            <template #cell="{ record }">
                                <a-link @click="handleScoreLogClick(record)">
                                    {{ record.score || 0 }}
                                </a-link>
                            </template>
                        </a-table-column>
                        <a-table-column title="卡云豆" data-index="card_score_total" :width="150">
                            <template #cell="{ record }">
                                {{ record.card_score_total || 0 }}
                            </template>
                        </a-table-column>
                        <a-table-column title="所属公司" data-index="company_name" :width="150">
                            <template #cell="{ record }">
                                {{ record.company_name || '-' }}
                            </template>
                        </a-table-column>

                        <a-table-column title="状态" data-index="in_black_text" :width="100">
                            <template #cell="{ record }">
                                <a-tag :color="getBlackStatusColor(record.in_black || 0)">
                                    {{ record.in_black_text || '正常' }}
                                </a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column title="地址数量" data-index="address_total" :width="120">
                            <template #cell="{ record }">
                                <a-link @click="handleAddressClick(record)">
                                    {{ record.address_total || 0 }}
                                </a-link>
                            </template>
                        </a-table-column>
                        <a-table-column title="随心付消费" data-index="biz_pay_record_total_money" :width="150">
                            <template #cell="{ record }">
                                {{ record.biz_pay_record_total_money || 0 }}
                            </template>
                        </a-table-column>
                        <a-table-column title="生活订单消费" data-index="biz_order_total_money" :width="150">
                            <template #cell="{ record }">
                                {{ record.biz_order_total_money || 0 }}
                            </template>
                        </a-table-column>
                        <a-table-column title="严选消费" data-index="order_total_money" :width="150">
                            <template #cell="{ record }">
                                {{ record.order_total_money || 0 }}
                            </template>
                        </a-table-column>

                        <a-table-column title="配货员" data-index="is_store_worker" :width="100">
                            <template #cell="{ record }">
                                
                                <a-link @click="changeExpressSendUser(record)">
                                    {{ record.is_store_worker == 1 ? '是' : '否' }}
                                </a-link>
                            </template>
                        </a-table-column>

                        <a-table-column title="是否VIP" data-index="vip_at" :width="180" />
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="操作" :width="100" fixed="right">
                            <template #cell="{ record }">
                                <a-space>
                                    <a-link type="text" @click="handleBlackStatusClick(record)">
                                        黑名单
                                    </a-link>
                                </a-space>
                            </template>
                        </a-table-column>
                        
                    </template>
                </a-table>
            </a-space>
        </a-card>
    </div>
    <a-modal
        v-model:visible="scoreDrawerVisible"
        title="充值套餐购买记录"
        :width="850"
        :footer="false"
        unmountOnClose
    >
        <a-table
            :data="scoreDrawerData"
            :loading="scoreDrawerLoading"
            :pagination="scoreDrawerPagination"
            :bordered="{ cell: true }"
            :scroll="{ x: 1300 }"
            row-key="id"
            @page-change="onScoreDrawerPageChange"
            @page-size-change="onScoreDrawerPageSizeChange"
        >
            <template #columns>
                <a-table-column title="ID" data-index="id" :width="80" />
                <a-table-column title="商户订单号" data-index="out_trade_no" :width="180" :ellipsis="true" :tooltip="true" />
            <a-table-column title="充值云豆" data-index="score" :width="120" />
            <a-table-column title="状态" data-index="status_text" :width="100" />
            <a-table-column title="创建时间" data-index="created_at" :width="180" />
            <a-table-column title="支付时间" data-index="paid_at" :width="180" />
            <a-table-column title="微信交易号" data-index="transaction_id" :width="180" :ellipsis="true" :tooltip="true" />
            
            </template>
            
        </a-table>
    </a-modal>

    <!-- 黑名单设置模态框 -->
    <a-modal
        v-model:visible="blackStatusDrawerVisible"
        title="黑名单设置"
        :width="700"
        unmountOnClose
    >
    <template #footer>
                <a-space>
                    
                    <a-button @click="blackStatusDrawerVisible = false">取消</a-button>
                    <a-button type="primary" @click="handleUpdateBlackStatus" :loading="blackStatusLoading">
                        确认更新
                    </a-button>
                </a-space>
            </template>
        <a-form :model="blackStatusForm" layout="vertical">
            <a-form-item label="用户信息">
                <a-descriptions :data="blackStatusUserInfo"  bordered />
            </a-form-item>
            <a-form-item label="黑名单状态">
                <a-radio-group v-model="blackStatusForm.in_black" direction="vertical">
                    <a-radio :value="0">正常</a-radio>
                    <a-radio :value="1">禁言</a-radio>
                    <a-radio :value="2">禁止下单</a-radio>
                </a-radio-group>
            </a-form-item>
            
        </a-form>
    </a-modal>

    <a-modal
        v-model:visible="chargeScoreVisible"
        title="充值/提现"
        :width="500"
    >
        <template #footer>
            <a-space>

                <a-button @click="chargeScoreVisible = false">取消</a-button>
                <a-button type="primary" @click="doChargeScoreForm" :loading="chargeScoreLoading">
                    确定
                </a-button>
            </a-space>
        </template>
        <a-form :model="chargeScoreForm" layout="vertical">
            <a-form-item label="充值云豆(正数充值/负数提现)" field="score">
                <a-input-number v-model="chargeScoreForm.score"  :step="1" />

            </a-form-item>

            <a-form-item label="备注说明" field="comment">
                <a-input v-model="chargeScoreForm.comment" />
            </a-form-item>

        </a-form>
    </a-modal>

    <!-- 地址管理模态框 -->
    <a-drawer
        v-model:visible="addressDrawerVisible"
        title="地址管理"
        :width="850"
        :footer="false"
        unmountOnClose
    >
        <a-table
            :data="addressDrawerData"
            :loading="addressDrawerLoading"
            :pagination="addressDrawerPagination"
            :bordered="{ cell: true }"
            :scroll="{ x: 1300 }"
            row-key="id"
            @page-change="onAddressDrawerPageChange"
            @page-size-change="onAddressDrawerPageSizeChange"
        >
                         <template #columns>
                 <a-table-column title="ID" data-index="id" :width="80" />
                 <a-table-column title="收货人" data-index="name" :width="120" />
                 <a-table-column title="手机号" data-index="phone" :width="150" />
                 <a-table-column title="省份" data-index="province" :width="100" />
                 <a-table-column title="城市" data-index="city" :width="100" />
                 <a-table-column title="区县" data-index="district" :width="100" />
                 <a-table-column title="详细地址" data-index="detail" :width="200">
                     <template #cell="{ record }">
                         <a-typography-paragraph :ellipsis="{ rows: 2, showTooltip: true }">
                             {{ record.detail }}
                         </a-typography-paragraph>
                     </template>
                 </a-table-column>
                 <a-table-column title="默认地址" data-index="is_default_text" :width="100">
                     <template #cell="{ record }">
                         <a-tag :color="record.is_default ? 'green' : 'gray'">
                             {{ record.is_default_text }}
                         </a-tag>
                     </template>
                 </a-table-column>
                 <a-table-column title="创建时间" data-index="created_at" :width="180" />
                 <a-table-column title="操作" align="center" :width="120" fixed="right">
                     <template #cell="{ record }">
                         <a-space size="mini">
                             <a-popconfirm position="left" content="确定要删除这个地址吗？" @ok="handleAddressDelete(record.id)">
                                 <a-link status="danger">
                                     删除
                                 </a-link>
                             </a-popconfirm>
                         </a-space>
                     </template>
                 </a-table-column>
             </template>
        </a-table>
    </a-drawer>


    <a-drawer
        v-model:visible="scoreLogDrawerVisible"
        title="云豆日志列表"
        :width="850"
    >
        <template #footer>
            <a-space>
                <a-button type="primary" shape="round" @click="handleChargeScoreClick">
                    充值/提现
                </a-button>
                <a-button type="primary" shape="round" @click="handleScoreClick">
                    充值套餐购买记录
                </a-button>
            </a-space>
        </template>

        <a-table
            :data="scoreLogDrawerData"
            :loading="scoreLogDrawerLoading"
            :pagination="scoreLogDrawerPagination"
            :bordered="{ cell: true }"
            row-key="id"
            @page-change="onScoreLogDrawerPageChange"
            @page-size-change="onScoreLogDrawerPageSizeChange"
        >
            <template #columns>
                <a-table-column title="ID" data-index="id" :width="80" />
                <a-table-column title="积分" data-index="score" :width="80" />
                <a-table-column title="类型" data-index="type" :width="120">
                    <template #cell="{ record }">
                        {{ record.type === 'credit' ? '云豆余额' : '卡云豆' }}
                    </template>
                </a-table-column>
                <a-table-column title="方向" data-index="dir" :width="80">
                    <template #cell="{ record }">
                        <a-tag :color="record.dir === 1 ? 'green' : 'red'">
                            {{ record.dir === 1 ? '存入' : '取出' }}
                        </a-tag>
                    </template>
                </a-table-column>
                <a-table-column title="备注" data-index="comment" />
                <a-table-column title="操作文本" data-index="action_text" :width="120" />
                <a-table-column title="创建时间" data-index="created_at" :width="180" />
            </template>
        </a-table>
    </a-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryMemberList, MemberRecord, updateMemberBlackStatus, updateMemberExpressSendUser } from '@/api/member';
import {chargeScore, queryScoreChargeList, ScoreChargeRecord} from '@/api/scoreCharge';
import { queryAddressList, AddressRecord, delAddress } from '@/api/address';
import { queryScoreLogList, ScoreLogRecord } from '@/api/scoreLog';

const router = useRouter();
const { loading, setLoading } = useLoading(true);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

const generateFormData = () => {
    return {
        id: 0,
    };
};

const formData = ref(generateFormData());

const searchForm = ref({
    phone: '',
});

const renderData = ref<MemberRecord[]>([]);
const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryMemberList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            phone: searchForm.value.phone,
        });
        renderData.value = data.list;
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取用户列表失败');
    } finally {
        setLoading(false);
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const handleSearch = () => {
    pagination.current = 1;
    fetchData();
};

const resetSearch = () => {
    searchForm.value.phone = '';
    pagination.current = 1;
    fetchData();
};

const scoreDrawerVisible = ref(false);
const scoreDrawerLoading = ref(false);
const scoreDrawerData = ref<ScoreChargeRecord[]>([]);
const scoreDrawerPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
});
const scoreDrawerUserId = ref<number | null>(null);

// 黑名单相关状态
const blackStatusDrawerVisible = ref(false);
const blackStatusLoading = ref(false);
const blackStatusForm = reactive({
    user_id: 0,
    in_black: 0,
});
const blackStatusUserInfo = ref<any[]>([]);

const fetchScoreChargeList = async (userId: number, current = 1, pageSize = 10) => {
    scoreDrawerLoading.value = true;
    try {
        const { data } = await queryScoreChargeList({
            user_id: userId,
            current,
            pageSize,
        });
        scoreDrawerData.value = data.list;
        scoreDrawerPagination.total = data.total;
    } catch (err) {
        Message.error('获取充值记录失败');
    } finally {
        scoreDrawerLoading.value = false;
    }
};

const handleScoreClick = () => {
    scoreDrawerUserId.value = currentUserRecord.value.id;
    scoreDrawerPagination.current = 1;
    scoreDrawerVisible.value = true;
    fetchScoreChargeList(currentUserRecord.value.id);
};

const onScoreDrawerPageChange = (current: number) => {
    scoreDrawerPagination.current = current;
    if (scoreDrawerUserId.value) {
        fetchScoreChargeList(scoreDrawerUserId.value, current, scoreDrawerPagination.pageSize);
    }
};

const onScoreDrawerPageSizeChange = (pageSize: number) => {
    scoreDrawerPagination.pageSize = pageSize;
    scoreDrawerPagination.current = 1;
    if (scoreDrawerUserId.value) {
        fetchScoreChargeList(scoreDrawerUserId.value, 1, pageSize);
    }
};

// 黑名单相关方法
const getBlackStatusColor = (inBlack: number) => {
    switch (inBlack) {
        case 0:
            return 'green';
        case 1:
            return 'orange';
        case 2:
            return 'red';
        default:
            return 'default';
    }
};

const handleBlackStatusClick = (record: MemberRecord) => {
    blackStatusForm.user_id = record.id;
    blackStatusForm.in_black = record.in_black || 0;
    
    // 设置用户信息显示
    blackStatusUserInfo.value = [
        { label: '用户ID', value: record.id },
        { label: '昵称', value: record.nickname || '-' },
        { label: '手机号', value: record.phone || '-' },
        { label: '当前状态', value: record.in_black_text || '正常' },
    ];
    
    blackStatusDrawerVisible.value = true;
};

const handleUpdateBlackStatus = async () => {
    blackStatusLoading.value = true;
    try {
        await updateMemberBlackStatus({
            user_id: blackStatusForm.user_id,
            in_black: blackStatusForm.in_black,
        });
        Message.success('黑名单状态更新成功');
        blackStatusDrawerVisible.value = false;
        fetchData(); // 刷新列表
    } catch (err) {
        Message.error('黑名单状态更新失败');
    } finally {
        blackStatusLoading.value = false;
    }
};

const handleAddressClick = (record: MemberRecord) => {
    addressDrawerUserId.value = record.id;
    addressDrawerPagination.current = 1;
    addressDrawerVisible.value = true;
    fetchAddressList(record.id);
};

// 地址管理相关状态
const addressDrawerVisible = ref(false);
const addressDrawerLoading = ref(false);
const addressDrawerData = ref<AddressRecord[]>([]);
const addressDrawerPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
});
const addressDrawerUserId = ref<number | null>(null);

const fetchAddressList = async (userId: number, current = 1, pageSize = 10) => {
    addressDrawerLoading.value = true;
    try {
        const { data } = await queryAddressList({
            user_id: userId,
            current,
            pageSize,
        });
        addressDrawerData.value = data.list;
        addressDrawerPagination.total = data.total;
    } catch (err) {
        Message.error('获取地址列表失败');
    } finally {
        addressDrawerLoading.value = false;
    }
};

const onAddressDrawerPageChange = (current: number) => {
    addressDrawerPagination.current = current;
    if (addressDrawerUserId.value) {
        fetchAddressList(addressDrawerUserId.value, current, addressDrawerPagination.pageSize);
    }
};

const onAddressDrawerPageSizeChange = (pageSize: number) => {
    addressDrawerPagination.pageSize = pageSize;
    addressDrawerPagination.current = 1;
    if (addressDrawerUserId.value) {
        fetchAddressList(addressDrawerUserId.value, 1, pageSize);
    }
};

const handleAddressDelete = async (id: number) => {
    try {
        await delAddress(id);
        Message.success('删除地址成功');
        if (addressDrawerUserId.value) {
            fetchAddressList(addressDrawerUserId.value, addressDrawerPagination.current, addressDrawerPagination.pageSize);
        }
    } catch (err) {
        Message.error('删除地址失败');
    }
};

// 积分交易明细
const currentUserRecord = ref({});
const scoreLogDrawerVisible = ref(false);
const handleScoreLogClick = (record: MemberRecord) => {
    scoreLogDrawerVisible.value = true;
    currentUserRecord.value = record;
    fetchScoreLogList(currentUserRecord.value.id);
}

const scoreLogDrawerLoading = ref(false);
const scoreLogDrawerData = ref<ScoreLogRecord[]>([]);
const scoreLogDrawerPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
});

const fetchScoreLogList = async (userId: number, current = 1, pageSize = 10) => {
    scoreLogDrawerLoading.value = true;
    try {
        const { data } = await queryScoreLogList({
            user_id: currentUserRecord.value.id,
            current,
            pageSize,
        });
        scoreLogDrawerData.value = data.list;
        scoreLogDrawerPagination.total = data.total;
    } catch (err) {
        Message.error('获取积分交易明细失败');
    } finally {
        scoreLogDrawerLoading.value = false;
    }
};

const onScoreLogDrawerPageChange = (current: number) => {
    scoreLogDrawerPagination.current = current;
    if (currentUserRecord.value.id) {
        fetchScoreLogList(currentUserRecord.value.id, current, scoreLogDrawerPagination.pageSize);
    }
};

const onScoreLogDrawerPageSizeChange = (pageSize: number) => {
    scoreLogDrawerPagination.pageSize = pageSize;
    scoreLogDrawerPagination.current = 1;
    if (currentUserRecord.value.id) {
        fetchScoreLogList(currentUserRecord.value.id, 1, pageSize);
    }
};

/**
 * 充值或提现
 */
const currentUserId = ref(0);
const chargeScoreForm = ref({
    score:0,
    user_id:0,
    comment:''
});
const chargeScoreVisible = ref(false);
const chargeScoreLoading = ref(false);
const handleChargeScoreClick = async ()=>{
    chargeScoreVisible.value = true;
    currentUserId.value = currentUserRecord.value.id;
}
const doChargeScoreForm = async (done:any)=>{
    chargeScoreLoading.value = true;
    chargeScoreForm.value.user_id = currentUserId.value;
    await chargeScore(chargeScoreForm.value);

    chargeScoreForm.value.score = 0;
    chargeScoreForm.value.comment = '';

    Message.success('充值或提现成功');
    chargeScoreVisible.value = false;
    fetchScoreLogList(currentUserRecord.value.id);
    done();
}

// 更改用户是否是配货员功能
const changeExpressSendUser = (record: MemberRecord) => {
    updateMemberExpressSendUser({
            user_id: record.id
    }).then(() => {
        Message.success('更新成功');
        fetchData();
    }).catch(() => {
        Message.error('更新失败');
    });
}

onMounted(() => {
    fetchData();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}
</style>

<script lang="ts">
export default {
    name: 'UserIndex',
};
</script>